package com.lube;

import com.lube.codec.MessageDecoder;
import com.lube.codec.MessageEncoder;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * TCP 客户端
 * 
 * @author caizhiping
 * @date 2017年1月24日 下午2:48:32
 */
public class Client {
	private final static String HOST = "127.0.0.1";
	private final static int PORT = 1885;

	public static void main(String[] args) throws Exception {
		EventLoopGroup workerGroup = new NioEventLoopGroup();

		try {
			Bootstrap b = new Bootstrap();
			b.group(workerGroup);
			b.channel(NioSocketChannel.class);
			b.option(ChannelOption.SO_KEEPALIVE, true);
			b.handler(new ChannelInitializer<SocketChannel>() {
				@Override
				public void initChannel(SocketChannel ch) throws Exception {
					ch.pipeline().addLast(new IdleStateHandler(0, 20, 0));
					
					ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
					
					// 添加解码器
					ch.pipeline().addLast(new MessageDecoder());
					// 添加编码器
					ch.pipeline().addLast(new MessageEncoder());

					ch.pipeline().addLast(new ClientHandler());
				}
			});

			ChannelFuture f = b.connect(HOST, PORT).sync();

			f.channel().closeFuture().sync();
		} finally {
			workerGroup.shutdownGracefully();
		}
	}
}
